package com.blog.cloud.auth.oauth.utils;

import com.blog.cloud.auth.oauth.cache.AuthSource;
import com.blog.cloud.auth.oauth.cache.AuthStateCache;
import com.blog.cloud.auth.oauth.config.AuthConfig;
import com.blog.cloud.auth.oauth.enums.AuthResponseStatus;
import com.blog.cloud.auth.oauth.exception.AuthException;
import com.blog.cloud.auth.oauth.cache.AuthDefaultSource;
import com.blog.cloud.auth.oauth.model.AuthCallback;
import me.zhyd.oauth.utils.GlobalAuthUtils;
import org.apache.commons.lang3.StringUtils;

public class AuthChecker {
    public static boolean isSupportedAuth(AuthConfig config, AuthSource source) {
        boolean isSupported = StringUtils.isNotEmpty(config.getClientId()) && StringUtils.isNotEmpty(config.getClientSecret());
        if (isSupported && AuthDefaultSource.ALIPAY == source) {
            isSupported = StringUtils.isNotEmpty(config.getAlipayPublicKey());
        }

        if (isSupported && AuthDefaultSource.WECHAT_ENTERPRISE == source) {
            isSupported = StringUtils.isNotEmpty(config.getAgentId());
        }

        return isSupported;
    }

    public static void checkConfig(AuthConfig config, AuthSource source) {
        String redirectUri = config.getRedirectUri();
        if (!config.isIgnoreCheckRedirectUri()) {
            if (StringUtils.isEmpty(redirectUri)) {
                throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source);
            } else if (!GlobalAuthUtils.isHttpProtocol(redirectUri) && !GlobalAuthUtils.isHttpsProtocol(redirectUri)) {
                throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source);
            } else if (AuthDefaultSource.ALIPAY == source && GlobalAuthUtils.isLocalHost(redirectUri)) {
                throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI, source);
            }
        }
    }

    public static void checkCode(AuthSource source, AuthCallback callback) {
        if (source != AuthDefaultSource.TWITTER) {
            String code = callback.getCode();
            if (source == AuthDefaultSource.ALIPAY) {
                code = callback.getAuth_code();
            } else if (source == AuthDefaultSource.HUAWEI) {
                code = callback.getAuthorization_code();
            }

            if (StringUtils.isEmpty(code)) {
                throw new AuthException(AuthResponseStatus.ILLEGAL_CODE, source);
            }
        }
    }

    public static void checkState(String state, AuthSource source, AuthStateCache authStateCache) {
        if (source != AuthDefaultSource.TWITTER) {
            if (StringUtils.isEmpty(state) || !authStateCache.containsKey(state)) {
                throw new AuthException(AuthResponseStatus.ILLEGAL_STATUS, source);
            }
        }
    }

}
